<%--
  Created by IntelliJ IDEA.
  User: YGQ
  Date: 2020-11-17
  Time: 16:44
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java"
         isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <%
        pageContext.setAttribute("APP_PATH", request.getContextPath());
    %>
    <%--
        不以 / 开始的相对路径，访问资源时以当前资源路径为基准
        以 / 开始的相对路径，访问资源时以服务器路径为基准，需要加上项目名
    --%>
    <%--引入 jQuery--%>
    <script type="text/javascript"
            src="${APP_PATH}/static/js/jquery-1.12.4.min.js"></script>
    <%--引入 Bootstrap--%>
    <link href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css"
          rel="stylesheet">
    <script src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>
    <title>员工列表</title>
</head>
<body>

<%--修改员工模态框--%>
<div class="modal fade" id="empUpdateModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="updateModalLabel">修改员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empNameUpdateStatic"
                               class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <p class="form-control-static"
                               id="empNameUpdateStatic"></p>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="empGender"
                                       id="empGenderUpdateInput1" value="M"
                                       checked="checked">
                                男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="empGender"
                                       id="empGenderUpdateInput2" value="F">
                                女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empEmailUpdateInput"
                               class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control"
                                   name="empEmail" id="empEmailUpdateInput"
                                   placeholder="email@example.com">
                            <span id="updateHelpBlock2"
                                  class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empDeptUpdateSelect"
                               class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-10">
                            <select class="form-control"
                                    id="empDeptUpdateSelect"
                                    name="departmentId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    关闭
                </button>
                <button type="button" class="btn btn-primary" id="empUpdateBtn">
                    更新
                </button>
            </div>
        </div>
    </div>
</div>

<%--新增员工模态框--%>
<div class="modal fade" id="empAddModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-label="Close"><span
                        aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="addModalLabel">新增员工</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">
                    <div class="form-group">
                        <label for="empNameAddInput"
                               class="col-sm-2 control-label">姓名</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control"
                                   name="empName" id="empNameAddInput"
                                   placeholder="">
                            <span id="helpBlock1" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <label class="radio-inline">
                                <input type="radio" name="empGender"
                                       id="empGenderAddInput1" value="M"
                                       checked="checked">
                                男
                            </label>
                            <label class="radio-inline">
                                <input type="radio" name="empGender"
                                       id="empGenderAddInput2" value="F">
                                女
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empEmailAddInput"
                               class="col-sm-2 control-label">邮箱</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control"
                                   name="empEmail" id="empEmailAddInput"
                                   placeholder="email@example.com">
                            <span id="helpBlock2" class="help-block"></span>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="empDeptAddSelect"
                               class="col-sm-2 control-label">部门</label>
                        <div class="col-sm-10">
                            <select class="form-control" id="empDeptAddSelect"
                                    name="departmentId">

                            </select>
                        </div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    关闭
                </button>
                <button type="button" class="btn btn-primary" id="empSaveBtn">
                    保存
                </button>
            </div>
        </div>
    </div>
</div>

<div class="container">
    <%--标题行--%>
    <div class="row">
        <div class="col-md-12">
            <h1>SSM-CRUD</h1>
        </div>
    </div>

    <%--按钮--%>
    <div class="row">
        <div class="col-md-4 col-md-offset-8">
            <button type="button" class="btn btn-primary btn-sm" id="empAddBtn">
                <span class="glyphicon glyphicon-plus"
                      aria-hidden="true"></span>
                新增
            </button>
            <button type="button" class="btn btn-danger btn-sm"
                    id="empDeleteAllBtn">
                <span class="glyphicon glyphicon-trash"
                      aria-hidden="true"></span>
                删除
            </button>
        </div>
    </div>

    <%--显示表格数据--%>
    <div class="row">
        <div class="col-md-12">
            <table class="table table-striped table-hover" id="empsTable">
                <thead>
                <tr>
                    <th>
                        <label><input type="checkbox" id="checkAll"></label>
                    </th>
                    <th>#</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>邮箱</th>
                    <th>部门</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody>

                </tbody>
            </table>
        </div>
    </div>

    <%--显示分页信息--%>
    <div class="row">
        <%--分页文字信息--%>
        <div class="col-md-12 text-center" id="pageInfoArea">

        </div>
        <%--分页条--%>
        <div class="col-md-12 text-center" id="pageNavArea">

        </div>
    </div>
</div>
<script type="text/javascript">
    let totalRecord, currentPage;
    // 页面加载完成后，发送 AJAX 请求获取数据
    $(function () {
        toPage(1);
    });

    function toPage(toPageNum) {
        $.ajax({
            url: "${APP_PATH}/employees",
            data: "pageNum=" + toPageNum,
            type: "GET",
            success: function (result) {
                // 解析并显示数据
                buildEmpsTable(result);
                // 解析并显示分页信息
                buildPageInfo(result);
                // 解析并显示导航条
                buildPageNav(result);
            }
        });
    }

    // 解析并显示数据
    function buildEmpsTable(result) {
        // 先清空表格
        $("#empsTable tbody").empty();

        var emps = result.extend.pageInfo.list;
        $.each(emps, function (index, item) {
            var checkBoxTd = $("<td><label><input type='checkbox' class='checkItem'></label></td>");
            var empIdTd = $("<td></td>").append(item.empId);
            var empNameTd = $("<td></td>").append(item.empName);
            var empGenderTd = $("<td></td>").append(item.empGender == 'M' ? "男" : "女");
            var empEmailTd = $("<td></td>").append(item.empEmail);
            var deptNameTd = $("<td></td>").append(item.department.deptName);
            /*
            <button type="button" class="btn btn-danger btn-sm"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除
            </button>
             */
            // var editBtn = $("<button></button>").addClass("btn btn-info btn-sm")
            //     .append($("<span></span>").addClass("glyphicon glyphicon-pencil"))
            //     .append("编辑");
            // var deleteBtn = $("<button></button>").addClass("btn btn-danger btn-sm")
            //     .append($("<span></span>").addClass("glyphicon glyphicon-trash"))
            //     .append("删除");
            var editBtn = $(
                "<button type='button' class='btn btn-info btn-sm edit-btn'><span class='glyphicon glyphicon-pencil' aria-hidden='true'></span> 编辑</button>"
            );
            // 为编辑按钮添加一个自定义属性，表示当前员工id
            editBtn.attr("edit-id", item.empId);
            var deleteBtn = $(
                "<button type='button' class='btn btn-danger btn-sm delete-btn'><span class='glyphicon glyphicon-trash' aria-hidden='true'></span> 删除</button>"
            );
            // 为删除按钮添加一个自定义属性，表示当前员工id
            deleteBtn.attr("delete-id", item.empId);
            var btnTd = $("<td></td>").append(editBtn).append(" ").append(deleteBtn);

            $("<tr></tr>").append(checkBoxTd).append(empIdTd).append(empNameTd)
                .append(empGenderTd).append(empEmailTd).append(deptNameTd).append(btnTd)
                .appendTo("#empsTable tbody");
        });
    }

    // 解析并显示分页信息
    function buildPageInfo(result) {
        $("#pageInfoArea").empty();
        $("#pageInfoArea").append("当前第 " + result.extend.pageInfo.pageNum + " 页，" +
            "共 " + result.extend.pageInfo.pages + " 页，" +
            "共 " + result.extend.pageInfo.total + " 条记录");
        totalRecord = result.extend.pageInfo.total;
        currentPage = result.extend.pageInfo.pageNum;
    }

    // 解析并显示导航条
    function buildPageNav(result) {
        $("#pageNavArea").empty();

        var ul = $("<ul></ul>").addClass("pagination");

        // var firstPageLi = $("<li></li>").append($("<a></a>").append("首页").attr("href", "#"));
        var firstPageLi = $("<li></li>").append($("<a></a>").append("首页"));
        firstPageLi.click(function () {
            toPage(1);
        });
        var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
        prePageLi.click(function () {
            toPage(result.extend.pageInfo.prePage);
        });
        if (result.extend.pageInfo.hasPreviousPage == false) {
            firstPageLi.addClass("disabled");
            prePageLi.addClass("disabled");
        } else {
            var firstPageLi = $("<li></li>").append($("<a></a>").append("首页"));
            firstPageLi.click(function () {
                toPage(1);
            });
            var prePageLi = $("<li></li>").append($("<a></a>").append("&laquo;"));
            prePageLi.click(function () {
                toPage(result.extend.pageInfo.prePage);
            });
        }
        ul.append(firstPageLi).append(prePageLi);

        $.each(result.extend.pageInfo.navigatepageNums, function (index, item) {
            var numLi = $("<li></li>").append($("<a></a>").append(item));
            if (item == result.extend.pageInfo.pageNum) {
                numLi.addClass("active");
            }
            numLi.click(function () {
                toPage(item);
            });
            ul.append(numLi);
        });

        var nextPageLi = $("<li></li>").append($("<a></a>").append("&raquo;"));
        var lastPageLi = $("<li></li>").append($("<a></a>").append("末页"));
        if (result.extend.pageInfo.hasNextPage == false) {
            nextPageLi.addClass("disabled");
            lastPageLi.addClass("disabled");
        } else {
            nextPageLi.click(function () {
                toPage(result.extend.pageInfo.nextPage);
            });
            lastPageLi.click(function () {
                toPage(result.extend.pageInfo.pages);
            });
        }
        ul.append(nextPageLi).append(lastPageLi);

        var navEle = $("<nav aria-label='Page navigation'></nav>");
        navEle.append(ul);
        navEle.appendTo("#pageNavArea");
    }

    /**
     * 重置表单
     */
    function resetFrom(ele) {
        // 清空表单数据
        $(ele)[0].reset();
        // 清楚表单样式
        $(ele).find("*").removeClass("has-success has-error");
        $(ele).find(".help-block").text("");
    }

    // 调用添加员工模态框
    $("#empAddBtn").click(function () {
        // 先清空表单，数据和样式都要重置
        resetFrom("#empAddModal form");
        // 发送 AJAX 请求查询部门信息
        getDepts("#empDeptAddSelect");
        // 弹出模态框
        $("#empAddModal").modal({
            backdrop: "static"
        });
    });

    /**
     * 查询部门信息，用于 select 列表
     */
    function getDepts(ele) {
        $(ele).empty();
        $.ajax({
            url: "${APP_PATH}/depts",
            type: "GET",
            async: false,
            success: function (result) {
                $.each(result.extend.depts, function () {
                    var optionEle = $("<option></option>")
                        .attr("value", this.deptId)
                        .append(this.deptName);
                    optionEle.appendTo(ele);
                });
            }
        });
    }

    /**
     * AJAX 校验姓名
     */
    function validateEmpName() {
        var empName = $("#empNameAddInput").val();
        var vaResult;
        // 发送 AJAX 请求校验用户名是否可用
        $.ajax({
            url: "${APP_PATH}/checkUser",
            type: "POST",
            data: "empName=" + empName,
            // 这里设为了同步，暂时还没有想到其他解决办法
            async: false,
            success: function (result) {
                if (result.code == 200) {
                    showValidateMsg("#empNameAddInput", "success", result.extend.vaMsg);
                    vaResult = true;
                } else {
                    showValidateMsg("#empNameAddInput", "error", result.extend.vaMsg);
                    vaResult = false;
                }
            }
        });
        return vaResult;
    }

    $("#empNameAddInput").blur(function () {
        validateEmpName();
    });

    /**
     * 前端正则表达式校验邮箱
     */
    function validateEmpEmail(ele) {
        // 校验邮箱
        var email = $(ele).val();
        var regEmail = /^([A-Za-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/;
        if (!regEmail.test(email)) {
            // alert("邮箱格式不正确！");
            showValidateMsg(ele, "error", "邮箱格式不正确！");
            return false;
        } else {
            showValidateMsg(ele, "success", "");
            return true;
        }
    }

    $("#empEmailAddInput").blur(function () {
        validateEmpEmail("#empEmailAddInput");
    });

    /**
     * 显示校验信息
     * @param ele 元素
     * @param status 校验状态
     * @param msg 显示信息
     */
    function showValidateMsg(ele, status, msg) {
        // 先清除校验状态
        $(ele).parent().removeClass("has-success has-error");
        // 再进行校验
        if ("success" == status) {
            $(ele).parent().addClass("has-success");
            $(ele).next("span").text(msg);
        } else if ("error" == status) {
            $(ele).parent().addClass("has-error");
            $(ele).next("span").text(msg);
        }
    }

    // 点击保存新增员工信息
    $("#empSaveBtn").click(function () {
        // alert(122);
        if (!validateEmpEmail("#empEmailAddInput")) {
            return false;
        }
        // alert(233);
        if (!validateEmpName()) {
            return false;
        }
        // alert(566);

        // 保存数据
        $.ajax({
            url: "${APP_PATH}/employees",
            type: "POST",
            data: $("#empAddModal form").serialize(),
            success: function (result) {
                if (result.code == 200) {
                    // 成功
                    // 关闭模态框
                    $("#empAddModal").modal('hide');
                    // 到末页显示刚保存的数据
                    // toPage(Number.MAX_SAFE_INTEGER);
                    toPage(9999999);
                } else {
                    // 失败
                    if (undefined != result.extend.fieldErrors.empName) {
                        showValidateMsg("#empNameAddInput", "error", result.extend.fieldErrors
                            .empName);
                    }
                    if (undefined != result.extend.fieldErrors.empEmail) {
                        showValidateMsg("#empEmailAddInput", "error", result.extend
                            .fieldErrors.empEmail);
                    }
                }
            }
        });
    });

    /**
     * 修改员工
     */
    $(document).on("click", ".edit-btn", function () {
        // 查出部门信息
        getDepts("#empUpdateModal select");
        // 查出并显示员工信息
        getEmpById($(this).attr("edit-id"));
        // 将员工id传递给模态框更新按钮
        $("#empUpdateBtn").attr("edit-id", $(this).attr("edit-id"));
        // 显示模态框
        $("#empUpdateModal").modal({
            backdrop: "static"
        });
    });

    function getEmpById(empId) {
        $.ajax({
            url: "${APP_PATH}/employees/" + empId,
            type: "GET",
            async: true,
            success: function (result) {
                // console.log(result);
                var empData = result.extend.employee;
                $("#empNameUpdateStatic").text(empData.empName);
                $("#empEmailUpdateInput").val(empData.empEmail);
                $("#empUpdateModal input[name=empGender]").val([empData.empGender]);
                // $("#empUpdateModal select").val([empData.departmentId]);
                $("#empUpdateModal select").val(empData.departmentId);
            }
        });
    }

    // 点击更新，更新员工信息
    $("#empUpdateBtn").click(function () {
        // 验证邮箱
        if (!validateEmpEmail("#empEmailUpdateInput")) {
            return false;
        }
        // 发送 AJAX 请求保存数据
        $.ajax({
            url: "${APP_PATH}/employees/" + $(this).attr("edit-id"),
            // 方法一
            // type: "POST",
            // data: $("#empUpdateModal form").serialize() + "&_method=PUT",
            // 方法二，请求方式直接写 PUT，需要配置 web.xml HttpPutFormContentFilter
            type: "PUT",
            data: $("#empUpdateModal form").serialize(),
            success: function (result) {
                // alert(result.msg);
                $("#empUpdateModal").modal("hide");
                toPage(currentPage);
            }
        });
    });

    /**
     * 删除员工
     */
    // 删除单个
    $(document).on("click", ".delete-btn", function () {
        // 确认对话框
        var deleteEmpName = $(this).parents("tr").find("td:eq(2)").text();
        if (confirm("确认删除【" + deleteEmpName + "】吗？")) {
            // 确认删除，发送 AJAX 请求删除
            $.ajax({
                url: "${APP_PATH}/employees/" + $(this).attr("delete-id"),
                type: "DELETE",
                success: function (result) {
                    alert(result.msg);
                    toPage(currentPage);
                }
            });
        }
    });
    // 全选、全不选
    $("#checkAll").click(function () {
        // prop用于原生属性，attr用于自定义属性
        $(".checkItem").prop("checked", $(this).prop("checked"));
    });
    $(document).on("click", ".checkItem", function () {
        var flag = $(".checkItem:checked").length == $(".checkItem").length;
        $("#checkAll").prop("checked", flag);
    });
    // 点击删除多个
    $("#empDeleteAllBtn").click(function () {
        var empNames = "", empIds = "";
        $.each($(".checkItem:checked"), function () {
            empNames += $(this).parents("tr").find("td:eq(2)").text() + ", ";
            empIds += $(this).parents("tr").find("td:eq(1)").text() + "-";
        });
        empNames = empNames.substring(0, empNames.length - 2);
        empIds = empIds.substring(0, empIds.length - 1);
        if (confirm("确认删除【" + empNames + "】吗？")) {
            // 发送 AJAX 完成删除
            $.ajax({
                url: "${APP_PATH}/employees/" + empIds,
                type: "DELETE",
                success: function (result) {
                    alert(result.msg);
                    toPage(currentPage);
                }
            });
        }
    });
</script>
</body>
</html>
